<?php

namespace app\api\model;


use app\api\service\ToolService;
use traits\model\SoftDelete;

class MemberModel extends BaseModel
{
    use SoftDelete;
    protected $pk = 'id';
    protected $table = 'hs_member';
    protected static $tableName = 'member';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    protected $hidden = ['deletetime'];
    public function getCreateTimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }
    public function getUpdateTimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }
    //模型关联跟进记录
    public function memberfollowupinfo(){
       return $this->hasMany('app\admin\model\member\Follw','customer_id', 'id');
    }
    public static  function List($user_id,$params)
    {
        $user = UserModel::info($user_id);
        if(!$user['c_id']){
            return false;
        }
        $page = !empty($params['page']) ? $params['page'] : 1;
        $limit = !empty($params['limit']) ? $params['limit'] : 10;
        $list = self::field('id,company_name,legal_person_name,shareholder_name,phone1,updatetime,createtime,remark');
        if($params['type']==2){
            $list = $list->where('user_id', 0)->where('c_id', $user['c_id']);
        }else{
            //跟进信息展示 表关联  为写完
            $list = $list->with('memberfollowupinfo')->where('user_id', $user_id);
            if(!empty($params['status'])){
                $list = $list->where('status', $params['status']);
            }else{
                $list = $list->where('status',0);
            }
            // $list = $list->where('user_id',  $user_id);
        }
        // $list = $list->where('deletetime', '');
        if(!empty($params['shareholder_name'])){
            if (ctype_digit($params['shareholder_name'])) {
                $list = $list->where('phone1', 'like', '%' . $params['shareholder_name'] . '%');
            } else {
                $list = $list->where('company_name', 'like', '%' . $params['shareholder_name'] . '%')
                    ->whereOr('legal_person_name', 'like', '%' . $params['shareholder_name'] . '%');
            }
        }
        if($params['orderby']==1){
            $list =$list->order('createtime asc');
        }else if($params['orderby']==2){
            $list =$list->order('updatetime desc');
        }else if($params['orderby']==3){
            //随机
            $list = $list->orderRaw('rand()');
        }else{
            //倒叙 
            $list =$list->order('createtime desc');
        }
        $list = $list ->page((int)$page, (int)$limit)->select();
        return $list;
    }
}